package com.hanqian.kepler.quartz.util;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import com.hanqian.kepler.common.utils.BeanUtils;
import com.hanqian.kepler.common.utils.SpringUtils;
import com.hanqian.kepler.quartz.constant.ScheduleConstants;
import com.hanqian.kepler.quartz.entity.JobLog;
import com.hanqian.kepler.quartz.service.JobLogService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * 抽象quartz调用
 *
 * @author ruoyi
 */
public abstract class AbstractQuartzJob implements Job {
    private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);

    /**
     * 线程本地变量
     */
    private static ThreadLocal<Date> threadLocal = new ThreadLocal<>();

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        com.hanqian.kepler.quartz.entity.Job sysJob = new com.hanqian.kepler.quartz.entity.Job();
        Object jobObject = context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES);
        BeanUtils.copyBeanProp(sysJob, jobObject);

        try {
            before(context, sysJob);
            doExecute(context, sysJob);
            after(context, sysJob, null);
        } catch (Exception e) {
            log.error("任务执行异常  - ：", e);
            after(context, sysJob, e);
        }
    }

    /**
     * 执行前
     *
     * @param context 工作执行上下文对象
     * @param sysJob 系统计划任务
     */
    protected void before(JobExecutionContext context, com.hanqian.kepler.quartz.entity.Job sysJob) {
        threadLocal.set(new Date());
    }

    /**
     * 执行后
     *
     * @param context 工作执行上下文对象
     */
    protected void after(JobExecutionContext context, com.hanqian.kepler.quartz.entity.Job sysJob, Exception e) {
        Date startTime = threadLocal.get();
        threadLocal.remove();

        if(StrUtil.equals("1", sysJob.getIfLog())){
            final JobLog sysJobLog = new JobLog();
            sysJobLog.setName(sysJob.getName());
            sysJobLog.setJobGroup(sysJob.getJobGroup());
            sysJobLog.setInvokeTarget(sysJob.getInvokeTarget());
            sysJobLog.setStartTime(startTime);
            sysJobLog.setEndTime(new Date());
            long runMs = sysJobLog.getEndTime().getTime() - sysJobLog.getStartTime().getTime();
            sysJobLog.setJobMessage(sysJobLog.getName() + " 总共耗时：" + runMs + "毫秒");
            if (e != null) {
                sysJobLog.setStatus("0");
                String errorMsg = StrUtil.sub(ExceptionUtil.getMessage(e), 0, 2000);
                sysJobLog.setExceptionInfo(errorMsg);
            } else {
                sysJobLog.setStatus("1");
            }

            // 写入数据库当中
            SpringUtils.getBean(JobLogService.class).addJobLog(sysJobLog);
        }
    }

    /**
     * 执行方法，由子类重载
     *
     * @param context 工作执行上下文对象
     * @param sysJob 系统计划任务
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, com.hanqian.kepler.quartz.entity.Job sysJob) throws Exception;
}
